# Copyright (c) 2011 anatanokeitai.com(sakurai_youhei)
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# 
# The Software shall be used for Younger than you, not Older.
# 
import sys
import time
import urllib
try:
  import json
except ImportError,e:
  import simplejson as json

import pyacp
#from apiresponse import *


def search_library(return_type, max_results=50, 
                   selected_columns=[], search_criteria=[], sort_criteria_list=[],
                   count_only=False, distinct_only=False,
                   album_art_urls_redirects=False, next_results_token=None):
  """
  Operation: searchLibrary
  searchReturnType: TRACKS | ALBUMS | ARTISTS | GENRES
  nextResultsToken: ???
  """
  pass


def get_global_last_updated_date():
  session = pyacp.get_session()
  if not session.is_logined():
    raise pyacp.PyAmazonCloudPlayerError("Not logined %s"%session)

  params={
    "Operation":"getGlobalLastUpdatedDate"
  }

  return _base_requester(params).get("date")


def _error_check(resp_json):
  if resp_json.get("Error"):
    raise pyacp.PyAmazonCloudPlayerApiException(resp_json.get("Error"))


def _base_requester(params):
  session = pyacp.get_session()
  try:
    operation=params["Operation"]
  except TypeError,e:
    raise pyacp.PyAmazonCloudPlayerError("Operation is required in params")

  ps=params.copy()
  ps["ContentType"]="JSON"
  ps["customerInfo.customerId"]=session.customer_id
  ps["customerInfo.deviceId"]=session.device_id
  ps["customerInfo.deviceType"]=session.device_type

  end_point=pyacp.api_root
  resp_json=json.loads(pyacp.conn.do_post(
    end_point,
    body=urllib.urlencode(ps),
    headers={"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
  ))
  _error_check(resp_json)
  result=resp_json.get(operation+"Response").get(operation+"Result")

  return result






